<script setup lang="ts">
import {onMounted, ref, useTemplateRef, watchEffect} from "vue";

const open = ref(false);

function change() {
  open.value = !open.value;
}

const offsetX = ref(0);
const offsetY = ref(0);

const isDragging = ref(false);

// 第一个参数必须与模板中的 ref 值匹配
const container = useTemplateRef<HTMLInputElement>('container');

watchEffect(() => {
  console.log('offsetX', offsetX.value);
  console.log('offsetY', offsetY.value);
});

function mousedown(event: MouseEvent) {
  isDragging.value = true;
  offsetX.value = event.offsetX - (container.value?.offsetLeft ?? 0);
  offsetY.value = event.offsetY - (container.value?.offsetTop ?? 0);

}

function stopDrag(event: MouseEvent) {
  isDragging.value = false;
}


function mousemove(event: MouseEvent) {
  console.log('mousemove', event);
  if (isDragging.value) {
    if (container.value) {
      container.value.style.left = `${event.offsetX - offsetX.value}px'`;
      container.value.style.top = `${event.offsetY - offsetY.value}px`;
    }


  }

}


</script>

<template>
  <button @click="change">打卡弹框</button>
  <teleport to="body">
    <div class="inner" v-if="open" @mousemove="mousemove" @mousedown="mousedown" ref="container" @mouseup="stopDrag">
      <p>6666</p>
      <button @click="open=false" id="close">X</button>
    </div>
  </teleport>


</template>

<style scoped>
#close {
  position: absolute;
  top: 0;
  right: 0;
}

.inner {
  width: 400px;
  height: 400px;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 9999;
  position: fixed;
  top: 20%;
  left: 20%
}
</style>